﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace sinetd
{
    public class Client
    {
        public static string ConfigurationFile = "Client.config.xml";

        private static Configuration cfg;

        public static List<string[]> GetServices()
        {
            List<string[]> list = new List<string[]>();

            cfg = new Configuration();
            cfg.Load(ConfigurationFile);

            int i = 1;
            foreach (KeyValuePair<string, string> kvp in cfg.Prot2Serv)
            {
                list.Add(new string[] { (i++).ToString(), cfg.Services[kvp.Value].Name, cfg.Protocols[kvp.Key].Name, cfg.Protocols[kvp.Key].Config });
            }

            return list;
        }

        public static string Send(int index, string msg)
        {
            if (cfg == null)
            {
                cfg.Load(ConfigurationFile);
            }

            sinetd.Protocols.IProtocol prot = (sinetd.Protocols.IProtocol)cfg.Protocols[cfg.Prot2Serv.Keys.ElementAt(index - 1)];
            string answer;
            try
            {
                prot.Connect();
                prot.Send(msg);
                answer = prot.Recv();
            }
            catch (Exception ex)
            {
                answer = ex.Message;
            }
            finally
            {
                prot.Close();
            }
            return answer;
        }
    }
}
